<?php

namespace app\controller;

use think\Request;
use app\model\Product as ProductModel;
use think\response\Json;

class Product
{
    /**
     * 发布商品
     * @param Request $request
     * @return Json 商品信息
     */
    public function publishProduct(Request $request){
        // 接收参数（商品描述，商品图片，价格，位置，联系方式，发货方式）
        $productDescription = $request->post("productDescription","");
        $ProductImg = $request->post("ProductImg","");
        $price = $request->post("price","");
        $location = $request->post("location","");
        $tel = $request->post("tel","");
        $shippingMethod = $request->post("shippingMethod","");

        // 用户信息
        $user = $request->user ?? null;

        // 用户信息不存在
        if (is_null($user)){
            return json([
                'code' => 401,
                'msg' => '未登录'
            ]);
        }

        // 验证参数合法性
        if (empty($productDescription) || empty($ProductImg) || empty($price) || empty($location) || empty($tel)){
            return json([
                'code' => 400,
                'msg' => '参数不合法'
            ]);
        }

        if (is_array($ProductImg) && !empty($ProductImg)){
            
        }

        // 图片数组转为 Json 字符串
        $ProductImg = json_encode($ProductImg, JSON_UNESCAPED_UNICODE);

        try {
            $product = ProductModel::publishProduct(
                $user['id'], $productDescription, $ProductImg, $price, $location, $tel, $shippingMethod
            );


            // 返回商品发布的商品信息
            return json([
                'code' => 200,
                'msg' => '发布成功',
                'data' => $product->hidden(['user_id'])->toArray()
            ]);

        } catch (\Exception $e) {

            return json([
                'code' => 500,
                'msg' => '系统异常'
                ], 500);
        }
    }
}